import Taro from '@tarojs/taro'
/**
 * 音频管理器
 */
export default class AudioManager {
    bgAudio: Taro.BackgroundAudioManager
    data: string[]
    index: number
    playIndex: number
    total: number

    title: string
    singer: string
    coverImg: string

    audioListener: AudioListener

    constructor(title: string, singer: string, coverImg: string, data: string[]) {
        this.data = data
        this.index = -1
        this.total = this.data.length
        this.title = title
        this.singer = singer
        this.coverImg = coverImg
        this.initBackgroundAudioManager()
    }

    initBackgroundAudioManager = () => {
        this.bgAudio = Taro.getBackgroundAudioManager()
        this.bgAudio.title = this.title
        this.bgAudio.epname = this.title
        this.bgAudio.singer = this.singer
        this.bgAudio.coverImgUrl = this.coverImg
    }

    setAudioListener = (audioListener: AudioListener) => {
        this.audioListener = audioListener
        this.bgAudio.onPlay(this.audioListener.onPlay)
        this.bgAudio.onPause(this.audioListener.onPause)
        this.bgAudio.onStop(this.audioListener.onStop)
        this.bgAudio.onEnded(this.audioListener.onEnded)
        this.bgAudio.onError(this.audioListener.onError)
    }

    setPlayIndex = (index: number) => {
        this.playIndex = index
    }

    setSrc = () => {
        if (this.index !== this.playIndex || this.playIndex === 0) {
            if (this.isExists(this.playIndex)) {
                this.initBackgroundAudioManager()
                const url = this.data[this.playIndex]
                if (url && url !== '') {
                    this.bgAudio.src = url
                } else {
                    this.audioListener.onNotExists()
                }
                this.index = this.playIndex
            }
        } else {
            this.bgAudio.play()
        }
    }

    play = (index: number) => {
        setTimeout(() => {
            this.setPlayIndex(index)
            this.setSrc()
        }, 100)
    }

    pause = () => {
        if (!this.isPaused()) {
            this.bgAudio.pause()
        }
    }

    stop = () => {
        this.bgAudio.stop()
    }

    isPaused = (): boolean => {
        return this.bgAudio.paused
    }

    isExists = (index: number) => {
        return index >= 0 && index < this.total
    }

    destroy = () => {
        this.bgAudio.pause()
        this.bgAudio.stop()
    }
}

interface AudioListener {
    onNotExists: () => void
    onError: () => void
    onPlay: () => void
    onPause: () => void
    onStop: () => void
    onEnded: () => void
}
